#-*- coding:utf-8 -*-

import urllib
import urllib2
import json 
import pandas as pd
import time
#import datetime

def http_get(url,params,cloumns,filePtah):
	#转换成url编码格式(字符串)
	word = urllib.urlencode(params) 
	newurl = url + "?" + word
	headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
	request = urllib2.Request(newurl,headers = headers)
	response = urllib2.urlopen(request)
	data = response.read().decode('utf-8')
	jsonData = json.loads(data)
	df = pd.DataFrame(jsonData, columns=cloumns)
	print(df[:10]['date'])
	df['date'] = pd.to_datetime(pd.to_datetime(df['date'],unit='ms'))
	print(df[:10]['date'])
	df.to_csv(filePtah,index_label='no')
	
def http_post(url,params,cloumns,filePtah):
	#转换成url编码格式(字符串)
	headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
	params = json.dumps(params)
	request = urllib2.Request(url,data=params,headers = headers)
	response = urllib2.urlopen(request)
	data = response.read().decode('utf-8')
	jsonData = json.loads(data)
	df = pd.DataFrame(jsonData, columns=cloumns)
	df.to_csv(filePtah)
	
if __name__ == '__main__':
	#cloumns = ['date','date_ms','amount','price','type','tid']
	cloumns = ['date','open','high','low','close','volume']
	#Z:\rich\BTC_project\data
	url = 'https://www.okcoin.com/api/v1/kline.do'
	params = {'symbol':'btc_usd','type':'1day'}
	filePtah = 'Z:/rich/BTC_project/data/20190108.csv'
	http_get(url,params,cloumns,filePtah)
